"use client";
import { useState, useRef, useEffect } from "react";
import MDEditor from '@uiw/react-md-editor';
import { Input, Button } from "antd";
import "./index.css";
import './md.css'
const { TextArea } = Input;
let testDataString = "";
export default function Home() {
  const ref = useRef();
  let [outputValue, setOutputValue] = useState("");

  const getReaderText = (str) => {
    let matchStr = "";
    try {
      let resultList = str.match(/data:\s*({.*?})\s*\n/g);
      resultList &&
      resultList.forEach((_) => {
          const matchStrItem = _.match(/data:\s*({.*?})\s*\n/)[1];
          const data = JSON.parse(matchStrItem);
          matchStr += (data?.choices[0].delta?.content || '');
        });
    } catch (e) {
      console.log(e);
    }
    return matchStr;
  };

  const send = async () => {
    setOutputValue("");
    const url = "http://10.169.112.194:7100/v1/chat/completions";
    const data = {
      model: "chatglm2-6b",
      messages: [
        {
          role: "user",
          content: "请实现一个登陆功能",
        },
      ],
      temperature: 0.75,
      stream: true,
    };

    testDataString = "";
    const response = await fetch(url, {
      method: "POST",
      body: JSON.stringify(data),
      headers: {
        "Content-Type": "application/json",
      },
    });

    const encode = new TextDecoder("utf-8");
    const reader = response.body.getReader();
    while (true) {
      const { done, value } = await reader.read();
      const decodeText = encode.decode(value);
      if (done) {
        console.log(decodeText);
        break;
      }
      setOutputValue((str) => (str += getReaderText(decodeText)));
      console.log(ref.current.mdp.current)
       ref.current &&
        (ref.current.mdp.current.scrollTop =
          ref.current.mdp.current.scrollHeight);
    }
  };
  return (
    <main className="chat-container flex min-h-screen text-black flex-col items-center justify-between ">
      <h1>Chat GPT 打字机效果</h1>
      <MDEditor.Markdown source={outputValue}  className="markdown-body" ref={ref}/>
      <Button onClick={send}>发送请求</Button>
    </main>
  );
}
